'''
子界面
配置pn_plc
'''
import sys
import traceback

from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QPushButton, QVBoxLayout, \
    QWidget, QHBoxLayout, QHeaderView
from PyQt5.QtCore import Qt

from util.util import write_yaml

from log import logger
# import util.util as util
class NonMainTableWidget(QWidget):

    def __init__(self, parent=None, data= None):
        super().__init__(parent)
        self.data = data  # {pn: device_name}
        # self.data = {'CBL-500-120-S00-05':'p1',
        #              'CBL-50': 'p2'
        #              }
        self.save_yaml_path = 'config/pn2plc_config.yaml'

        self.table_widget = QTableWidget()
        self.init_table_widget()
        # table_widget_layout = QHBoxLayout()# 表格水平布局
        # table_widget_layout.addWidget(self.table_widget)

        self.add_row_button = QPushButton("添加新行")
        self.delete_row_button = QPushButton("删除选定行")

        # 设置按钮字体和大小
        font = QFont("Arial", 12)
        self.add_row_button.setFont(font)
        self.delete_row_button.setFont(font)

        # 设置按钮点击事件
        self.add_row_button.clicked.connect(self.add_new_row)
        self.delete_row_button.clicked.connect(self.delete_selected_row)

        # 创建水平布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(5)  # 设置按钮间的间距
        button_layout.addWidget(self.add_row_button)
        button_layout.addWidget(self.delete_row_button)

        # 创建主垂直布局
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.table_widget, stretch=1)  # 让表格占据大部分空间
        # main_layout.addLayout(table_widget_layout, stretch=1)  # 让表格占据大部分空间
        main_layout.addLayout(button_layout, stretch=0)  # 让按钮布局保持固定高度
        main_layout.setContentsMargins(5, 5, 5, 5)  # 设置四周内边距

        self.setLayout(main_layout)

        # 监听单元格内容改变事件，自动保存数据
        self.table_widget.itemChanged.connect(self.save_data_slot)

        self.setStyleSheet("""
                QPushButton {
                    min-width: 80px;
                    padding: 5px;
                    border-radius: 3px;
                    color: white;
                    background-color: dodgerblue;
                }
                QPushButton:hover {
                    background-color: darkblue;
                }
            """)  # 设置按钮样式
        self.setWindowTitle("PN_PLC_CONFIG")
        self.table_widget.horizontalHeader().setSectionResizeMode(
            QHeaderView.Interactive | QHeaderView.Stretch)  # 列宽自适应表格控件大小



    def init_table_widget(self):
        self.table_widget.setColumnCount(2)  # 设置列数
        self.table_widget.setHorizontalHeaderLabels(["PN", "点位"])  # 添加表头
        # self.table_widget.setColumnWidth(0, 1000)  # 设置指定列的宽度 px
        # self.table_widget.setColumnWidth(1, 1000)  # 设置指定列的宽度
        # 设置表格可编辑
        self.table_widget.setEditTriggers(QTableWidget.AllEditTriggers)

        # 添加初始数据（可选）
        for k,v in self.data.items():
            self.add_new_row(k, v)
        # 根据内容自动调整列宽和行高
        self.table_widget.resizeColumnsToContents()
        self.table_widget.resizeRowsToContents()


    def save_data_slot(self, item):
        # 这里仅为示例，实际应用中应将数据保存到数据库或文件等持久化存储中
        try:
            print(f"Saving updated data: {item.text()} at ({item.row()}, {item.column()})")
            k = self.table_widget.item(item.row(),0).text()
            v = self.table_widget.item(item.row(),1).text()
            print(f"k {k}, v {v}")
            dws = ('plc_config.PlaceStrap','plc_config.PlaceBat','plc_config.PlaceStrap',
                   'plc_config.PlaceCable','plc_config.PlaceInstruction','plc_config.PlaceLicence',
                   'plc_config.PlaceChDQ')
            if k in (' ', '') or v not in dws:
                logger.error(f'格式错误未保存，请检查格式； 第{item.row()+1}行 {k}: {v}')
                return
            self.data[k] = v
            # if not self.data.get(k):
            print(self.data)
            write_yaml(self.data, self.save_yaml_path)
            # # 根据内容自动调整列宽和行高
            # self.table_widget.resizeColumnsToContents()
            # self.table_widget.resizeRowsToContents()
        except:
            print(traceback.format_exc())

    def add_new_row(self, k='', v=''):
        self.table_widget.blockSignals(True) # 屏蔽信号
        row_count = self.table_widget.rowCount()
        self.table_widget.insertRow(row_count)  # 添加新行
        self.table_widget.setItem(row_count, 0, QTableWidgetItem(k))  # 设置新单元格内容
        self.table_widget.setItem(row_count, 1, QTableWidgetItem(v))  # 设置新单元格内容
        self.table_widget.blockSignals(False)

    def delete_selected_row(self):
        try:
            selected_rows = sorted(set(index.row() for index in self.table_widget.selectedIndexes()), reverse=True)
            for row in selected_rows:
                k = self.table_widget.item(row,0).text()
                self.data.pop(k, None)
                self.table_widget.removeRow(row)
                print(self.data)
            write_yaml(self.data, self.save_yaml_path)
        except:
            print(traceback.format_exc())

if __name__ == "__main__":
    # app = QApplication([])
    # window = MainWindow()
    # window.show()
    # sys.exit(app.exec_())


    app = QApplication([])
    dialog = NonMainTableWidget()
    # dialog.setWindowTitle("Table Dialog")
    dialog.setWindowModality(Qt.ApplicationModal)  # 设置对话框为模态窗口，防止用户与主窗口交互
    dialog.show()
    sys.exit(app.exec_())